import { api } from '@/api'

import useRouteStore from './route'
import useMenuStore from './menu'

function setCookie(cname, cvalue, day) {
    var d = new Date()
    if (day != null) {
        d.setTime(d.getTime() + (day * 60 * 60 * 1000))
        var expires = 'expires=' + d.toUTCString()
        document.cookie = cname + '=' + cvalue + '; ' + expires
    } else {

        d.setTime(d.getTime() + (24 * 60 * 60 * 1000))
        var expiresX = 'expires=' + d.toUTCString()
        document.cookie = cname + '=' + cvalue + '; ' + expiresX
    }

}

// 获取cookie
function getCookie(cname) {

    var name = cname + '='
    var ca = document.cookie.split(';')
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i]
        while (c.charAt(0) == ' ') c = c.substring(1)
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length)
    }
    return ''
}

// 清除cookie

function clearCookie(name) {
    setCookie(name, '', -1)
}

const useUserStore = defineStore(
    // 唯一ID
    'user',
    {
        state: () => ({
            account: getCookie('account') || localStorage.account || '',
            token: getCookie('token') || localStorage.token || '',
            permissions: []
        }),
        getters: {
            isLogin: state => {
                let retn = false

                if (state.token) {
                    if (state.token != 'undefined' || '') {
                        retn = true
                    }
                }
                return retn
            }
        },
        actions: {
            // 用户登入
            login(data) {
                return new Promise((resolve, reject) => {
                    // 通过 mock 进行登录
                    api.post('authentication', data, {
                    }).then(
                        res => {
                            setCookie('account', data.username)
                            setCookie('token', res)
                            // localStorage.setItem('account', data.username)
                            // localStorage.setItem('token', res)
                            this.account = data.username
                            this.token = res
                            resolve()
                        }).catch(error => {
                        reject(error)
                    })
                })
            },
            // 用户登出
            logout() {
                return new Promise(resolve => {
                    const routeStore = useRouteStore()
                    const menuStore = useMenuStore()
                    this.account = ''
                    this.token = ''
                    // localStorage.removeItem('account')
                    // localStorage.removeItem('token')
                    clearCookie('account')
                    clearCookie('token')
                    routeStore.removeRoutes()
                    menuStore.setActived(0)
                    resolve()
                })
            },
            // 获取我的权限 --未处理
            getPermissions() {
                return new Promise(resolve => {
                    // 通过 mock 获取权限
                    api.get('member/permission', {
                        baseURL: '/mock/',
                        params: {
                            account: this.account
                        }
                    }).then(res => {
                        this.permissions = res.data.permissions
                        resolve(res.data.permissions)
                    })
                })
            },
            // 新增用户
            addAccout(data) {
                return new Promise(resolve => {
                    api.post('users', {
                        name: data.name,
                        username: data.username,
                        password: data.password,
                        role: data.role ? data.role : null,
                        groupId: data.groupId
                    }, {
                        // baseURL: '/mock/'
                    }).then(() => {
                        resolve()
                    })
                })
            },
            // 获取用户列表分页信息
            getAccout(params) {
                return new Promise((resolve, reject) => {
                    api.get('users', {
                        params
                    }).then(res => {
                        resolve(res)
                    }).catch(error => {
                        reject(error)
                    })
                })
            },
            getAccoutTree(params) {
                return new Promise((resolve, reject) => {
                    api.get('user-groups/trees', {
                        params
                    }).then(res => {
                        resolve(res)
                    }).catch(error => {
                        reject(error)
                    })
                })
            },
            // 获取当前登陆用户信息

            getCurentAccout() {
                return new Promise((resolve, reject) => {
                    api.get('users/current', {
                    }).then(res => {
                        resolve(res)
                    }).catch(error => {
                        reject(error)
                    })
                })
            },
            // 更新用户信息

            editAccout(params) {
                return new Promise((resolve, reject) => {
                    api.put(`users/${params.id}/info`, {
                        name: params.name,
                        username: params.username,
                        role: params.role,
                        groupId: params.groupId
                    }).then(res => {
                        resolve(res)
                    }).catch(error => {
                        reject(error)
                    })
                })
            },
            // 更新用户密码

            editPassword(params) {
                return new Promise((resolve, reject) => {
                    api({
                        url: `users/${params.id}/password`,
                        method: 'put',
                        data: params.newpassword
                    }).then(res => {
                        resolve(res)
                    }).catch(error => {
                        reject(error)
                    })
                })
            },
            // 删除用户

            deleteAccout(id) {
                return new Promise((resolve, reject) => {
                    api.delete(`users/${id}`, {
                    }).then(res => {
                        resolve(res)
                    }).catch(error => {
                        reject(error)
                    })
                })
            },
            // 获取文件操作记录
            opearateRecords(params) {
                return new Promise((resolve, reject) => {
                    api.get(`files/operate-records`, { params
                    }).then(res => {
                        resolve(res)
                    }).catch(error => {
                        reject(error)
                    })
                })
            }
        }
    }
)

export default useUserStore
